package com.idenger.modules.edu.mobileWeb.practice;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.idenger.common.web.BaseController;
import com.idenger.modules.edu.entity.common.BaseResponseMsg;
import com.idenger.modules.edu.entity.common.ResponseMsg;
import com.idenger.modules.edu.entity.course.EduCourse;
import com.idenger.modules.edu.entity.enroll.EduEnroll;
import com.idenger.modules.edu.entity.practice.EduPractice;
import com.idenger.modules.edu.service.enroll.EduEnrollService;
import com.idenger.modules.edu.service.practice.EduPracticeService;
import com.idenger.modules.edu.service.practicsubject.EduPracticSubjectService;
import com.idenger.modules.edu.web.comm.Constant;
import com.idenger.modules.sys.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.idenger.common.utils.StringUtils;
import com.idenger.modules.edu.entity.exercisehistory.EduExerciseHistory;
import com.idenger.modules.edu.entity.practicsubject.EduPracticSubject;
import com.idenger.modules.edu.entity.selectiontitle.EduSelectionTitle;
import com.idenger.modules.edu.entity.user.EduUser;
import com.idenger.modules.edu.service.course.EduCourseService;
import com.idenger.modules.edu.service.exercisehistory.EduExerciseHistoryService;
import com.idenger.modules.edu.service.selectiontitle.EduSelectionTitleService;
import com.idenger.modules.sys.utils.UserUtils;

@Controller
@RequestMapping(value = "${mobilePath}/edu/practice/eduPractice")
public class MPracticeController extends BaseController {
	@Autowired
	private EduPracticeService eduPracticeService;
	@Autowired
	private EduPracticSubjectService eduPracticSubjectService;
	@Autowired
	private EduSelectionTitleService eduSelectionTitleService;
	@Autowired
	private EduEnrollService eduEnrollService;
	
	@Autowired
	private EduCourseService eduCourseService;
	@Autowired
	private EduExerciseHistoryService eduExerciseHistoryService;
	
	@ModelAttribute
	public EduPractice get(@RequestParam(required=false) String id) {
		EduPractice entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = eduPracticeService.get(id);
		}
		if (entity == null){
			entity = new EduPractice();
		}
		return entity;
	}

	@RequestMapping(value = "form")
	public String form(EduPractice eduPractice,HttpServletRequest request, HttpServletResponse response, Model model){
		EduPracticSubject eduPracticSubject = new EduPracticSubject();
		eduPracticSubject.setPracticeId(eduPractice.getId());
		//根据习题id查出习题题目关联表，再查出题目，set进eduPractice
		List<EduPracticSubject> list = eduPracticSubjectService.findList(eduPracticSubject);
		
		List<EduPracticSubject> list2 = new ArrayList<>();
		for(EduPracticSubject eduPracticSubject2 :list){
			EduSelectionTitle eduSelectionTitle = eduSelectionTitleService.get(eduPracticSubject2.getTitleId());
			eduPracticSubject2.setEduSelectionTitle(eduSelectionTitle);
			list2.add(eduPracticSubject2);
		}
		eduPractice.setPracticSubjectList(list2);
		BaseResponseMsg baseResponseMsg;
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		baseResponseMsg.addData(eduPractice);
		return renderString(response, baseResponseMsg);
	}
	
	/***
	 * 用户做题
	 * @param eduPractice
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "doPractice")
	public String doPractice(@RequestBody EduPractice eduPractice, HttpServletRequest request, HttpServletResponse response, Model model){
		BaseResponseMsg baseResponseMsg;
		EduUser eduUser = (EduUser) request.getAttribute("currentUser");
		List<EduPracticSubject> list = eduPractice.getPracticSubjectList();
		//计算总分
        BigDecimal score = new BigDecimal("0.00");
        score = score.setScale(2,BigDecimal.ROUND_HALF_DOWN);
        StringBuffer answer = new StringBuffer();
		for(EduPracticSubject eduPracticSubject : list){
			EduSelectionTitle eduSelectionTitle = eduPracticSubject.getEduSelectionTitle();
				//判断用户选的该题是否正确
				if(eduSelectionTitle.getUserOptions().equals(eduSelectionTitle.getTrueResult())){
					BigDecimal radioScore = new BigDecimal(eduPracticSubject.getScore());
					score = score.add(radioScore);
				}
				//将用户的全部题目的答案拼成一个StringBuffer
				answer.append(eduSelectionTitle.getId()+":"+eduSelectionTitle.getUserOptions()+";");
		}
		//保存用户做题记录
        EduExerciseHistory eduExerciseHostory = new EduExerciseHistory();
		eduExerciseHostory.setContent(answer.toString());
		//eduExerciseHostory.setUserId(eduUser.getId());
		eduExerciseHostory.setUserId(eduUser.getId());

		eduExerciseHostory.setScore(score.intValue());
		eduExerciseHostory.setPracticeId(eduPractice.getId());
		User user = UserUtils.getUser();
		eduExerciseHostory.setCreateBy(user);
		eduExerciseHostory.setUpdateBy(user);
		eduExerciseHistoryService.save(eduExerciseHostory);
		compareScore(eduPractice, eduUser);
		baseResponseMsg = new BaseResponseMsg(new ResponseMsg("0", "success"));
		Map map =new  HashMap();
		map.put("score",score);
		baseResponseMsg.addData(map);
		return renderString(response, baseResponseMsg);
	}
	//是否结课成功
	public void compareScore(EduPractice eduPractice,EduUser eduUser){
		//计算分值，改报名报状态
		EduCourse eduCourse =  eduCourseService.getCourse2(eduPractice.getId());
		EduEnroll eduEnroll2 = new EduEnroll();
		eduEnroll2.setUserid(eduUser.getId());
		eduEnroll2.setCurriculumId(eduCourse.getId());
		EduEnroll enSta = eduEnrollService.getEduEnrollByUserIdAndCourseId(eduEnroll2);
		if((Constant.EDUENROLL_STATUS_NO).equals(enSta.getStatus())){
			BigDecimal percentage = new BigDecimal("100");
			String sumScore1 ="0";
			if(StringUtils.isNotBlank(eduCourse.getSumScore())){
				sumScore1 = eduCourse.getSumScore();
			}
			//拿到视频有效分
			BigDecimal videoValidScore = getVideoValidScore(eduCourse,percentage,eduUser);
			//拿到练习的有效分
			BigDecimal practiceValidScore = getPracticeValidScore(eduCourse,percentage,eduUser);
			//实际有效总分
			BigDecimal sumValidScore =videoValidScore.add(practiceValidScore);
			sumValidScore = sumValidScore.setScale(2, BigDecimal.ROUND_DOWN); 
			BigDecimal sumScore = new BigDecimal(sumScore1);
			sumScore=sumScore.setScale(2, BigDecimal.ROUND_DOWN); 
			if(sumScore.compareTo(sumValidScore)==1){
				//不结课
			}else{
				//分值达到，可以结课，
				EduEnroll eduEnroll = new EduEnroll();
				eduEnroll.setCurriculumId(eduCourse.getId());
				eduEnroll.setUserid(eduUser.getId());
				EduEnroll enroll =	eduEnrollService.getEduEnrollByUserIdAndCourseId(eduEnroll);
				if(enroll != null){
					enroll.setStatus(Constant.EDUENROLL_STATUS_IS_OK);
					eduEnrollService.save(enroll);
				}
			}
		}
	}
		//视频有效分
		public BigDecimal getVideoValidScore(EduCourse eduCourse,BigDecimal percentage,EduUser eduUser){
			//视频
			String videoScore = "0";
			if(StringUtils.isNotBlank(eduCourse.getVideoScore())){
				videoScore = eduCourse.getVideoScore();
			}
			//拿到视频占比
			BigDecimal videoValidScorePercentage = new BigDecimal(videoScore);
			videoValidScorePercentage = videoValidScorePercentage.divide(percentage, 2, RoundingMode.HALF_UP);
			//拿到视频的有效分
			
			String videoValidScore1= eduCourseService.getVideoValidScore(eduUser.getId(),eduCourse.getId());
			if(StringUtils.isBlank(videoValidScore1)){
				videoValidScore1 = "0";
			}
			BigDecimal videoValidScore=new BigDecimal(videoValidScore1);
			videoValidScore=videoValidScore.setScale(2, BigDecimal.ROUND_DOWN); 
			videoValidScore = videoValidScore.multiply(videoValidScorePercentage);	
			return videoValidScore;
		}
		
		//课程有效分
		public BigDecimal getPracticeValidScore(EduCourse eduCourse,BigDecimal percentage,EduUser eduUser){
			//课程
			String practiceScore = "0";
			if(StringUtils.isNotBlank(eduCourse.getPracticeScore())){
				practiceScore = eduCourse.getPracticeScore();
			}
			//拿到课程占比
			BigDecimal practiceValidScorePercentage=new BigDecimal(practiceScore);
			practiceValidScorePercentage = practiceValidScorePercentage.divide(percentage, 2, RoundingMode.HALF_UP);
			//拿到练习的有效分
			
			String practiceValidScore1 = eduCourseService.getPracticeValidScore(eduUser.getId(),eduCourse.getId());
			if(StringUtils.isBlank(practiceValidScore1)){
				practiceValidScore1="0";
			}
			BigDecimal practiceValidScore=new BigDecimal(practiceValidScore1);
			practiceValidScore=practiceValidScore.setScale(2, BigDecimal.ROUND_DOWN);
			practiceValidScore = practiceValidScore.multiply(practiceValidScorePercentage);	
			return practiceValidScore;
		}

}
